import { Component, ViewEncapsulation } from '@angular/core';
import { ICellRendererAngularComp } from '@ag-grid-community/angular';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { getO } from '../../../utils/utils';

@Component({
  selector: 'apes-render-tag',
  template: `
    <div>
      <ng-container *ngFor="let tag of tagList">
        <ng-container *ngIf="showTagFormatter(tag) && tag.hasOwnProperty('tooltipFormatter')">
          <apes-tag apes-tooltip
                    [apesTooltipTitle]="titleTemplate"
                    [apesColor]="tag.color? tag.color : 'cyan'">{{tag.name}}</apes-tag>
          <ng-template #titleTemplate>
            <div [innerHTML]="getTooltipFormatter(tag)"></div>
          </ng-template>
        </ng-container>
        <ng-container *ngIf="showTagFormatter(tag) && !tag.hasOwnProperty('tooltipFormatter')">
          <apes-tag [apesColor]="tag.color? tag.color : 'cyan'">{{tag.name}}</apes-tag>
        </ng-container>
      </ng-container>
    </div>
  `,
  styles: [
      `

    `,
  ],
})
export class RenderTagComponent implements ICellRendererAngularComp {
  params: any;
  apesConfig: any;

  ctx: any = {};
  data: any = {};
  tagList: any[] = [];

  constructor(
    private expressionService: ExpressionService,
  ) {
  }

  refresh(params: any): boolean {
    return false;
  }

  agInit(params): void {
    this.params = params;
    this.ctx = params.context;
    this.apesConfig = this.extend(params);

    if (params.context) {
      this.ctx = params.context;
    }

    if (this.params.hasOwnProperty('colDef')) {
      this.data = this.params.data;
      this.tagList = getO(this.params.colDef.items);
    } else {
      this.data = this.params.node.data;
      this.tagList = getO(this.params['column']['colDef'].items);
    }
  }

  extend(data: any) {
    let result = {};
    for (let key in data) {
      let value = data[key];
      if (key === 'context') {
        result['ctx'] = value;
      } else {
        result[key] = value;
      }
    }
    return result;
  }

  showTagFormatter(tag): string {
    let expression = tag.valueFormatter || false;
    return this.expressionService.evaluate(expression, {
      context: this.ctx,
      model: this.ctx['model'],
      data: this.data,
    });
  }

  getTooltipFormatter(tag): string {
    let expression = tag.tooltipFormatter || tag.name;
    return this.expressionService.evaluate(expression, {
      context: this.ctx,
      model: this.ctx['model'],
      data: this.data,
    });
  }
}
